<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Telegram\Bot\Api;

  
class ApiController extends Controller
{
    public function test(){
        
        $cron = DB::table("tg_crontab")->where("status",1)->get();
        foreach ($cron as $Key){
            if( time() - strtotime($Key->updated_at) >= $Key->count_down){
                
                $group = DB::table("tg_group")->where("id",$Key->group_id)->first();
                $bot = DB::table("tg_bot")->where("id",$group->bot_id)->first();
                $keyword = DB::table("tg_keyword")->where("id",$Key->key_id)->first();
                
                $telegram = new Api($bot->bot_token);
                $response = $telegram->sendMessage([
                  'chat_id' => $group->chat_id,
                  'text' => $keyword->content
                ]);

                if($response){
                    $res = DB::table("tg_crontab")->where("id",$Key->id)->update(['updated_at'=>date("Y-m-d H:i:s")]);
                }
                
            }
        }




    }
    //
    public function pushmsg($bot_token,Request $request){
        
      
        $input = $request->all();
            
        if(!isset($input['update_id'])){
            return "code:20001,消息格式错误".json_encode($input);
        }
        
        $bot = DB::table("tg_bot")->where("bot_token",$bot_token)->first();
        if($bot->status == 0){
            return "code:20002 机器人未开启监听";
        }
        
        if(isset($input['message']['chat']['type']) && $input['message']['chat']['type'] == "private"){
            //私聊
            if(isset($input['message']['text'])){
                //文本
                $this->save_chat($input['message']['chat']['id'],$input['message']['chat']['first_name']." ".$input['message']['chat']['last_name'],$input['message']['chat']['type'],$input['message']['date'],$input['message']['text'],'',$bot->id); 
                $this->send_chat($input['message']['chat']['id'],$input['message']['text'],$bot->id);
                
            }else if(isset($input['message']['photo'])){
                //图片
                 $telegram = new Api($bot_token);
                 $response = $telegram->getFile(['file_id' => $input['message']['photo'][0]['file_id']]);
                 $response = json_decode($response,true);
                 $filepath = 'https://api.telegram.org/file/bot'.$bot_token.'/'.$response['file_path'];
                 $this->save_chat($input['message']['chat']['id'],$input['message']['chat']['first_name']." ".$input['message']['chat']['last_name'],$input['message']['chat']['type'],$input['message']['date'],$input['message']['caption']??"",$filepath,$bot->id);    
            }else{
                return "未识别私聊";
            }
            
        }else if(isset($input['message']['chat']['type']) && $input['message']['chat']['type'] == "supergroup"){
            //群组
            
            if(isset($input['message']['text'])){
                //文本
                $this->save_chat($input['message']['chat']['id'],$input['message']['chat']['title']."[".$input['message']['from']['first_name'].$input['message']['from']['last_name']."]",$input['message']['chat']['type'],$input['message']['date'],$input['message']['text'],'',$bot->id);
                $this->send_chat($input['message']['chat']['id'],$input['message']['text'],$bot->id);
            }else if(isset($input['sticker'])){
                //表情
                 $telegram = new Api($bot_token);
                 $response = $telegram->getFile(['file_id' => $input['message']['sticker']['thumb']['file_id']]);
                 $response = json_decode($response,true);
                 $filepath = 'https://api.telegram.org/file/bot'.$bot_token.'/'.$response['file_path'];
                 $this->save_chat($input['message']['chat']['id'],$input['message']['chat']['title']." ".$input['message']['chat']['last_name'],$input['message']['chat']['type'],$input['message']['date'],$input['sticker']['emoji']??"",$filepath,$bot->id);    
            }else{
                return "未识别群组";
            }
             
         
        }else if(isset($input['channel_post']['chat']['type']) && $input['channel_post']['chat']['type'] == "channel"){
            //频道
            
            if(isset($input['channel_post']['text'])){
                //文本
                 $this->save_chat($input['channel_post']['chat']['id'],$input['channel_post']['chat']['title'],$input['channel_post']['chat']['type'],$input['channel_post']['date'],$input['channel_post']['text'],$input['channel_post']['chat']['title'],$bot->id); 
                 $this->send_chat($input['channel_post']['chat']['id'],$input['channel_post']['text'],$bot->id);
            }else if(isset($input['channel_post']['photo'])){
                //图片
                 $telegram = new Api($bot_token);
                 $response = $telegram->getFile(['file_id' => $input['channel_post']['photo'][0]['file_id']]);
                 $response = json_decode($response,true);
                 $filepath = 'https://api.telegram.org/file/bot'.$bot_token.'/'.$response['file_path'];
                 $this->save_chat($input['channel_post']['chat']['id'],$input['channel_post']['chat']['title'],$input['channel_post']['chat']['type'],$input['channel_post']['date'],'',$filepath,$bot->id);    
            }else{
                return "未识别频道";
            }
            
            
            
        }else{
            return "未识别";
        }
         
        return true;
       
        
    }
    
    //私聊
    /*保存群或频道
    $message_id 消息id
    $username 用户名、群名
    $type 聊天类型
    $date 时间
    $content 聊天内容
    $images 聊天图片
    $bot_id 机器人id
    */
    protected function save_chat($chat_id,$username,$type,$date,$content,$images,$bot_id){
        
          DB::table("tg_msg_record")->insert([
            'chat_id'=> $chat_id,
            'bot_id'=>$bot_id,
            'type' => $type,
            'username'=>$username,
            'content'=>$content,
            'images'=>$images,
            'created_at'=>date("Y-m-d H:i:s",$date),
            'updated_at'=>date("Y-m-d H:i:s",$date),
            ]);
            
          if($type == "channel" || $type == "supergroup"){
              $chat = DB::table("tg_group")->where("chat_id",$chat_id)->first();
              if($chat){
                  $res = DB::table("tg_group")->where("id",$chat->id)->update(['title'=>$username]);
              }else{
                  $res = DB::table("tg_group")->insert([
                      'chat_id'=>$chat_id,
                      'bot_id'=>$bot_id,
                      'title'=>strstr($username,"[",true),
                      'created_at'=>date("Y-m-d H:i:s"),
                      'updated_at'=>date("Y-m-d H:i:s"),
                      ]);
              }
          }    
    }
    
    /*
    推送消息
    $chat_id 群Id或频道id
    $content 群名称或频道名称
    $bot_id 机器人id
    */
    protected function send_chat($chat_id,$content,$bot_id){
        
        $tg_keyword = DB::table("tg_keyword")->where("keyword",'like','%'.$content.'%')->where(["bot_id"=>$bot_id,'status'=>1])->first();
        if($tg_keyword){
            $bot_token = DB::table("tg_bot")->where("id",$bot_id)->value("bot_token");
            $telegram = new Api($bot_token);
            $response = $telegram->sendMessage([
              'chat_id' => $chat_id,
              'text' => $tg_keyword->content
            ]);
        }
         
    }
    
}
